export default {
    namespaced: true, //添加命名空间
    state: {
        name: 'cart模块',
        carts: []
    },
    mutations: {
        //添加到购物车
        //1.点击添加到购物车,需要将当前的商品展示到cart模块
        //2.库存需要-1
        //3.添加进来初始数量是1
        //4.重复添加的时候,让购物车对应的该数据数量+1
        SET_CART(state, payload) {
            //...
            // console.log(payload)

            //判断Carts有没有这条数据
            let target = state.carts.find(item => item.id === payload.id)

            if (!target) {
                //如果没有,创建一条添加进去
                let obj = {
                    id: payload.id,
                    title: payload.title,
                    price: payload.price,
                    count: 1
                }
                state.carts.push(obj)
            } else {
                //如果有,数量加1
                target.count++
            }
        },
        //移除购物车
        DECREASE_CART(state, payload) {
            //找到购物车对应的数据
            let target = state.carts.find(item => item.id === payload.id)
            //让数量减少
            target.count--

            //把数量为0的过滤掉

            state.carts = state.carts.filter(item => item.count !== 0)
        }
    },
    actions: {
        ADD_TO_CART({ commit }, payload) {
            //调用自己的mutation
            commit('SET_CART', payload)
            //调用Product模块中的mutation
            //非常重要!!!!!!!
            commit('Product/DECREASE_INVENTORY', payload, { root: true })
        },
        //移除购物车
        REMOVE_CART({ commit }, payload) {
            console.log(payload)
            commit('DECREASE_CART', payload)
            //调用Product模块的mutation
            commit('Product/INCREASE_INVENTORY', payload, { root: true })
        }
    },
    getters: {
        //计算总价格
        total(state) {
            return (state.carts.reduce((total, item) => {
                return total += item.price * item.count
            }, 0)).toFixed(2)
        }
    },
}